<template>
  <el-dialog :title="openLovPara.title" :visible.sync="open" width="650px"  append-to-body @close="closeDialog">

    <el-form :model="queryBody" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <template v-for="(item,k) in searchs">
        <el-form-item :label="item.label" label-width="85">
          <el-input v-model="searchColumn[item.prop]" :placeholder="'请输入'+item.label" clearable :key="k"
                    @keyup.enter.native="handleQuery"/>
        </el-form-item>
      </template>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery" v-if="showBtn">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery" v-if="showBtn">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="lovDataList" border header-cell-class-name="table_header_class" ref="multipleTable" highlight-current-row
              :row-key="getRowKey" @row-dblclick="dbClick" @current-change="singleChange" @selection-change="handleSelectionChange">
      <el-table-column type="selection" :reserve-selection="true" label="选择" width="60" v-if="!single"></el-table-column>
      <el-table-column type="index" label="序号"></el-table-column>
      <template v-for="(item,k) in openLovPara.columns"><!--循环遍历父组件传过来的column信息-->
        <el-table-column :prop="item.prop" :label="item.label" :width="item.width" :key="k" v-if="item.show==false?false:true"></el-table-column>
      </template>
    </el-table>

    <div style="padding: 10px 0">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryBody.pageNum"
                     :page-sizes="[5, 10, 15, 20]" :page-size="queryBody.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"
                     :pager-count="pagerCount">
      </el-pagination>
    </div>

    <div style="text-align: left;margin-left: 50px;">
      <el-button type="primary" @click="onSelectSubmit">确 定</el-button>
      <el-button @click="onSelectClose">取 消</el-button>
    </div>

  </el-dialog>

</template>

<script>

import request from '@/utils/request'

export default {
  name: "LovPlus",
  props: {
    openLovPara:Object
  },
  watch: {
    openLovPara: {
      handler(newVal, oldVal) {
        this.open = newVal.openLov;
        if(this.open){
          this.getList();
        }
      },
      //深度监控对象里面的值
      deep: true,
      //首次通过created去执行immediate: false设置未false
      immediate: false
    }
  },
  data() {
    return {
      // 是否显示弹出层
      open: false,
      dialogWidth:500,
      //分页条的个数展示，默认为5
      pagerCount: 5,
      //搜索框是否展示
      showSearch: true,
      //按钮是否展示,如果没有查询条件，按钮展示就没有意义
      showBtn: false,
      // 查询参数
      queryBody: {
        pageSize: 5,
        pageNum: 1,
      },
      searchs: [],
      //查询的column
      searchColumn:[],
      //lov查询出来的数据
      lovDataList:[],
      total: 0,
      //单选&多选 默认单选
      single: true,
      //多选值
      multipleSelection: [],
      //多选可以选择的条数，单选时无效
      resultSize: 20,
      //主键
      table_key: '',

    };
  },
  methods: {
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryBody.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      for (const key in this.searchColumn) {
        this.searchColumn[key] = ''
      }
      this.handleQuery();
    },
    /**获取列表组件*/
    getRowKey(row){
      return row[this.table_key]
    },
    /**列表选择改变时，仅用于单选*/
    singleChange(val) {
      this.currentRow = val;
    },
    /**列表选着改变 用于多选*/
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    /**分页组件每页条数改变*/
    handleSizeChange(val){
      //每次切换每页条数要把当前页设置为第一页
      this.queryBody = {pageNum:1,pageSize:val};
      this.getList();
    },
    /**分页组件当前页码改变*/
    handleCurrentChange(val){
      this.queryBody.pageNum = val;
      this.getList();
    },
    /** 获取table数据*/
    getList(){
      for (const key in this.searchColumn) {
        this.queryBody[key] = this.searchColumn[key]
      }
      request({
        url: this.openLovPara.queryUrl,
        method: 'get',
        params: this.queryBody
      }).then(res=>{
        let resuleFormat = this.openLovPara.resuleFormat;
        if (resuleFormat) {//自定义后端的返回格式
          for (const k in resuleFormat) {
            if (k == 'data') {
              this.lovDataList = this.getResult(resuleFormat[k], res)
            } else if (k == 'total') {
              this.total = this.getResult(resuleFormat[k], res)
            }
          }
        } else {//默认后端返回格式
          this.lovDataList = res.rows;
          this.total = res.total;
        }
      });
    },
    /**处理自定义的后端返回格式*/
    getResult(key, res){
      let result = res;
      let keys = key.split(".");
      for (const v of keys) {
        result = result[v]
      }
      return result;
    },
    /**列表双击事件*/
    dbClick(row) {
      if (this.single) {//单选 双击直接提交
        this.onSelectSubmit()
      } else {//多选的话，双击选中或者取消选中
        this.$refs.multipleTable.toggleRowSelection(row);
      }
    },
    /** 确认按钮逻辑*/
    onSelectSubmit(){
      if(this.single){//如果是单选的话
        let record = {};
        this.openLovPara.columns.forEach(item => {
          record[item.prop] = this.currentRow[item.prop]
        })
        this.openLovPara.submit && this.openLovPara.submit(record)
        //this.open = false;
        return
      }
      //多选
      let records = [];
      let checkArr = this.multipleSelection;
      if (checkArr.length <= 0) {
        this.$message.error("请至少选择一条记录")
        return
      }
      if (this.resultSize != checkArr.length) {
        this.$message.error("只能选择" + this.resultSize + "条记录")
        return
      }
      checkArr.forEach(row => {
        let record = {}
        this.openLovPara.columns.forEach(item => {
          record[item.prop] = row[item.prop]
        })
        records.push(record)
      })
      //调用父组件的回调函数
      this.openLovPara.submit && this.openLovPara.submit(records);
      //this.open = false;
    },
    /**取消按钮逻辑*/
    onSelectClose(){
      //调用父组件的回调函数
      this.openLovPara.cancel && this.openLovPara.cancel();
      //this.open = false;
    },
    //初始化查询列
    initSelectColumn() {
      this.dialogWidth = this.openLovPara.lovWidth&&this.openLovPara.lovWidth;
      let searchs = [];
      this.openLovPara.columns.forEach(item => {
        if (item.key) {
          this.table_key = item.prop
        }
        if (item.search) {
          searchs.push({
            prop: item.prop,
            label: item.label
          })
          this.$set(this.searchColumn, item.prop, '')
          this.showBtn = true
        }
      })
      this.searchs = searchs;
    },
    //Dialog关闭事件
    closeDialog(){
      this.onSelectClose();
    }
  },
  created() {
    this.initSelectColumn();
  }
}
</script>

<style>
.table_header_class {
  background-color: #D3DCE6 !important;
  color: black;
}
</style>

<!--调用示例-->
<!--
openLovPara:{
queryUrl:'/user/listByPage',
res:{
data:'rows',
total:'total'
},
//默认查询参数
defaultParam:{
roleId: 2//用户
},
//多选可选这的条数，单选
resultSize:2,
//表示单选
single:true,
//确定的回调
submit:(data)=>{
if(!Array.isArray(data)){
this.userName=data.name
this.userId=data.id
}else{
this.userName=data[0].name
this.userId=data[0].id
}
},
//取消的回调
cancel:()=>{

},
columns:[
{prop:'id',label:'ID',key:true,show:true},
{prop:'name',label:'名字',width:200,search:true},
{prop:'no',label:'账号',width:200,},
{prop:'phone',label:'电话',}
]
},-->
